﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;

namespace Web.Infrastructure.Mvc.FileUpload
{
    public class UploadHelper
    {
        public static string Save(HttpPostedFileBase file, string path)
        {
            var root = string.Format("~/Upload/{0}/", path);
            var phicyPath = HostingEnvironment.MapPath(root);
            Directory.CreateDirectory(phicyPath);
            var fileName = Md5(file.InputStream) + file.FileName.Substring(file.FileName.LastIndexOf('.'));
            file.SaveAs(phicyPath + fileName);
            return fileName;
        }

        public static string ToJson(object input)
        {
            return JsonConvert.SerializeObject(input);
        }

        public static string Md5(Stream input)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] hash = md5.ComputeHash(input);
                return BitConverter.ToString(hash).Replace("-", "").ToLower();
            }
        }

        public static string GetUrlFromVisualPath(string url)
        {
            return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
                UrlHelper.GenerateContentUrl(url, new HttpContextWrapper(HttpContext.Current));
        }
    }
}